package cn.zhuangcloud.newversion.githook;

import com.jfinal.kit.JsonKit;
import com.jfinal.kit.Ret;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;

@SuppressWarnings("unchecked")
class HookService {

    static final HookService me = new HookService();
    private static final Logger log = LoggerFactory.getLogger(HookService.class);

    Ret handle(String request) {
        HashMap<String, String> map = JsonKit.parse(request, HashMap.class);
        if (!map.get("password").equals("KXDEQ7U9GG8VLP1X2c1cL2aPbXJ263K2")) {
            return Ret.by("success", false);
        }
        try {
            char[] buffer = new char[8192];
            int len;
            StringBuilder sb = new StringBuilder();
            ProcessBuilder pb = new ProcessBuilder("/root/Tomcat_apps/java_web_test_src/javaweb-test/update.sh");
            
            Process ps = pb.start();
            try (BufferedReader br = new BufferedReader(new InputStreamReader(ps.getInputStream()))) {
                while ((len = br.read(buffer)) != -1) {
                    sb.append(buffer, 0, len);
                }
            }
            try (BufferedReader br = new BufferedReader(new InputStreamReader(ps.getErrorStream()))) {
                while ((len = br.read(buffer)) != -1) {
                    sb.append(buffer, 0, len);
                }
            }
            return Ret.by("yangsen", sb);


           /* Process ps = Runtime.getRuntime().exec("/root/Tomcat_apps/java_web_test_src/javaweb-test/update.sh");
            try (BufferedReader br = new BufferedReader(new InputStreamReader(ps.getInputStream()))) {
                while ((len = br.read(buffer)) != -1) {
                    sb.append(buffer, 0, len);
                }
            }
            try (BufferedReader br = new BufferedReader(new InputStreamReader(ps.getErrorStream()))) {
                while ((len = br.read(buffer)) != -1) {
                    sb.append(buffer, 0, len);
                }
            }
            return Ret.by("yangsen", sb);*/
        } catch (IOException e) {
            log.warn(e.getMessage(), e);
            return Ret.by("IOException", true);
        }
    }

}
